/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.cms;

import net.dgg.dggcloud.core.cache.CacheManager;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.common.tree.Tree;
import net.dgg.dggcloud.service.common.util.StringUtility;
import net.dgg.dggcloud.service.jrcrm.constant.CommonConstant;
import net.dgg.dggcloud.service.jrcrm.dao.cms.TreeBookDao;
import net.dgg.dggcloud.service.jrcrm.entity.cms.TreeBook;
import net.dgg.dggcloud.service.entity.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: TreeBookService
 * @Description: 字典管理逻辑
 * @Author 汤宏
 * @date 2017/11/3 10:22
 */
@Service
public class TreeBookService extends BaseService {
    @Autowired
    private TreeBookDao treeBookDao;

    /**
     * 查询所有字典，用于树
     * @param map
     * @return
     */
    public List<Map> queryTreeBookList(Map map){
        List<Map> retMap = treeBookDao.queryTreeBookList(map);
        return retMap;
    }


    /**
     * 查询字典为事业部id的数据
     * @param map
     * @return
     */
    public List<Map> orgQueryTreeBookList(Map map){
        List<Map> retMap = treeBookDao.orgQueryTreeBookList(map);
        return retMap;
    }

    /**
     *
     * @param map
     * @return count
     */
    public Integer orgCountQueryTreeBookList(Map map){
        Integer count = treeBookDao.orgCountQueryTreeBookList(map);
        return count;
    }

    public List<Map> queryTreeBookListByCodeToSelect(Map map){
        List<Map> retMap = treeBookDao.queryTreeBookListByCodeToSelect(map);
        return retMap;
    }

    public List<Map> queryTreeBookListByCodeToSelectAll(Map map){
        List<Map> retMap = treeBookDao.queryTreeBookListByCodeToSelectAll(map);
        return retMap;
    }


    /**
     * 新增更新字典
     *
     * @param treeBook
     */
    public TreeBook saveOrUpdateTreeBook(TreeBook treeBook,User loger) {
        try {
            treeBook.setCode(treeBook.getCode().replace(" ", ""));
            treeBook.setName(treeBook.getName().replace(" ", ""));
            Long pid = treeBook.getPid();
            if (null == pid) {
                throw new BizException("请先选择父级字典", 10001);
            }
            if (StringUtils.isEmpty(treeBook.getCode())) {
                throw new BizException("请输入字典编码", 10001);
            }
            if (StringUtils.isEmpty(treeBook.getName())) {
                throw new BizException("请输入字典名称", 10001);
            }

            if(0L<pid){
                //通过id查找到父级字典
                TreeBook parentTreeBook = this.repository.get(TreeBook.class, pid);
                if (null == parentTreeBook) {
                    throw new BizException("父级字典不存在", 10001);
                }
                if(parentTreeBook.getStatus()==0){
                    throw new BizException("上级字典未启用！请先设置上级启用", 10001);
                }
                treeBook.setPcode(parentTreeBook.getCode());
                treeBook.setLevels(parentTreeBook.getLevels() + "_" + parentTreeBook.getId());
            }else{
                treeBook.setPcode("-1");
                treeBook.setLevels("-1");
            }
            if(null != treeBook.getId()){
                if(treeBook.getStatus()==0){
                    Map map = new HashMap();
                    map.put("levels", treeBook.getLevels() + "_" + treeBook.getId());
                    map.put("status", 1);
                    Long count = treeBookDao.countTreeBookChild(map);
                    if(null!=count&&count.intValue()>0) {
                        throw new BizException("字典下有启用的子级！不能设置禁用", 10001);
                    }
                }
                TreeBook treeBookUp = this.repository.get(TreeBook.class, treeBook.getId());
                treeBookUp.setCode(treeBook.getCode());
                treeBookUp.setName(treeBook.getName());
                treeBookUp.setPid(treeBook.getPid());
                treeBookUp.setPcode(treeBook.getPcode());
                treeBookUp.setLevels(treeBook.getLevels());
                treeBookUp.setDescription(treeBook.getDescription());
                treeBookUp.setStatus(treeBook.getStatus());
                treeBookUp.setSort(treeBook.getSort());
                treeBookUp.setExt1(treeBook.getExt1());
                treeBookUp.setExt2(treeBook.getExt2());
                treeBookUp.setExt3(treeBook.getExt3());
                treeBookUp.setExt4(treeBook.getExt4());
                treeBookUp.setExt5(treeBook.getExt5());
                treeBookUp.setUpdaterUser(loger);
                treeBookUp.setType(treeBook.getType());
                treeBookUp.setCostType(treeBook.getCostType());
                Map smap = new HashMap();
                smap.put("code", treeBook.getCode());
                smap.put("id", treeBook.getId());
                if (treeBookDao.queryTreeBookRepeat(smap) > 0) {
                    throw new BizException("字典编码已存在", 10001);
                }
                this.repository.saveOrUpdate(treeBookUp);
            }else{
                Map smap = new HashMap();
                smap.put("code", treeBook.getCode());
                if (treeBookDao.queryTreeBookRepeat(smap) > 0) {
                    throw new BizException("字典编码已存在", 10001);
                }
                long id = this.keyWorker.nextId();
                treeBook.setId(id);
                treeBook.setCreateUser(loger);
                this.repository.save(treeBook);
            }
            //删除redis中缓存的字典列表，
            CacheManager.getOperator().deleteByPattern(CommonConstant.TREEBOOK_LIST_KEY);
            return treeBook;
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            throw new BizException(e.getLocalizedMessage(), 10001);
        }
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public TreeBook queryTreeBookObj(Long id){
        TreeBook treeBook = this.repository.get(TreeBook.class,id);
        return treeBook;
    }


    /**
     * 根据分类编码查询下级
     *
     * @param code code
     * @param type 1：根据分类编码查询下级第一级分类（用于Select选择）
     *             2：根据分类编码查询所有下级分类（用于Tree选择无父级的）
     *             3：根据分类编码查询所有下级分类包含自己（用于Tree选择有父级的）
     *            4：根据分类编码查询所有下级分类（用于Tree选择无父级的）,查询包含禁用的字典
     * @return
     */
    public List<Map> queryTreeBookListByCode(String code, Integer type) {
        List<Map> resultList ;
        TreeBook treeBook = new TreeBook();
        Map map = new HashMap();
        try {
            if (StringUtils.isEmpty(code)) {
                throw new BizException("编码不能为空", 10001);
            }
            if (null == type) {
                throw new BizException("查询类型不能为空", 10001);
            }
            resultList =   CacheManager.getOperator().get(CommonConstant.TREEBOOK_LIST_KEY+code+":"+type, List.class);
            if (null != resultList) {
                return resultList;
            }
            resultList = new ArrayList();

            if (1 == type) {
                map.put("code", code);
                resultList = treeBookDao.queryTreeBookListByCodeToSelect(map);
            }
            if (2 == type) {
                treeBook.setCode(code);
                treeBook = this.repository.get(treeBook);
                if(null!=treeBook){
                    map.put("levels", treeBook.getLevels() + "_" + treeBook.getId());
                    map.put("status", 1);
                    resultList = treeBookDao.queryTreeBookListByCodeToTree(map);
                }
            }
            if (3 == type) {
                treeBook.setCode(code);
                treeBook = this.repository.get(treeBook);
                if(null!=treeBook) {
                    map.put("id", treeBook.getId());
                    map.put("levels", treeBook.getLevels() + "_" + treeBook.getId());
                    map.put("status", 1);
                    resultList = treeBookDao.queryTreeBookListByCodeToParentTree(map);
                }
            }
            if (4 == type) {
                treeBook.setCode(code);
                treeBook = this.repository.get(treeBook);
                if(null!=treeBook){
                    map.put("levels", treeBook.getLevels() + "_" + treeBook.getId());
                    resultList = treeBookDao.queryTreeBookListByCodeToTree(map);
                }
            }
            if (5 == type) {
                treeBook.setCode(code);
                treeBook = this.repository.get(treeBook);
                if(null!=treeBook) {
                    map.put("id", treeBook.getId());
                    map.put("levels", treeBook.getLevels() + "_" + treeBook.getId());
                    resultList = treeBookDao.queryTreeBookListByCodeToParentTree(map);
                }
            }
            CacheManager.getOperator().put(CommonConstant.TREEBOOK_LIST_KEY+code+":"+type, resultList);
            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询失败！" + e.getMessage());
            throw new BizException("查询失败！", 10001);
        }
    }

    /**
     * 根据编码查询字典
     * @param code
     * @return
     */
    public TreeBook queryTreeBookByCode(String code) {
        TreeBook treeBook = null;
        try {
            treeBook = new TreeBook();
            treeBook.setCode(code);
            treeBook = this.repository.get(treeBook);
        } catch (Exception e) {
            logger.error("查询失败！" + e.getMessage());
            throw new BizException("查询失败！", 10001);
        }
        return treeBook;
    }
    /**
     * 根据子编码查询父级字典
     * @param code
     * @return
     */
    public TreeBook queryTreeBookParentByCode(String code) {
        TreeBook parentTreeBook = null;
        try {
            TreeBook treeBook = new TreeBook();
            treeBook.setCode(code);
            treeBook = this.repository.get(treeBook);
            if(null != treeBook){
                parentTreeBook = this.repository.get(TreeBook.class,treeBook.getId());
            }
        } catch (Exception e) {
            logger.error("查询失败！" + e.getMessage());
            throw new BizException("查询失败！", 10001);
        }
        return parentTreeBook;
    }
    /**
     * 删除
     * @param id
     * @return
     */
    public void deleteTreeBookBy(Long id) {
        try {
            TreeBook treeBook =this.queryTreeBookObj(id);
            Map map = new HashMap();
            map.put("levels", treeBook.getLevels() + "_" + treeBook.getId());
            Long count = treeBookDao.countTreeBookChild(map);
            if(null!=count&&count.intValue()>0){
                throw new BizException("删除失败，字典下有子级！", 10001);
            }else{
                //删除redis中缓存的字典列表，
                CacheManager.getOperator().deleteByPattern(CommonConstant.TREEBOOK_LIST_KEY);
                CacheManager.getOperator().delete(CommonConstant.TREEBOOK_KEY+treeBook.getCode());
                this.repository.delete(treeBook);
            }
        } catch (Exception e) {
            throw new BizException(e.getMessage(), 10001);
        }
    }


    /**
     * 根据父级的code获取本级和子级code的集合，并以'号将code包起来，用于数据库in查询
     * @param code 父级code
     * @return
     */
    public String queryTreeBookCodesByCode(String code) {
        List<Map> list = queryTreeBookListByCode(code,5);
        StringBuffer codes = new StringBuffer();
        for (Map map : list) {
            codes.append(",").append("'").append(map.get("code").toString()).append("'");
        }
        return  StringUtils.isNotBlank(codes.toString()) ?  codes.substring(1): code;
    }



    /**
     * 修改或者保存
     */
    public void updateTreeBook(TreeBook treeBook) {
       repository.saveOrUpdate(treeBook);
    }

}
